<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\model\Users;
use think\App;
use utils\Helper;

class Sms extends BaseController
{
    protected Captcha $captcha;

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    //
    public function send_login_sms()
    {
        $phone = $this->request->post('phone');
        $user = Users::where('phone', $phone)->find();
        if (empty($user)) return $this->error('账号不存在');
        if (!empty(cache("login_sms_send_{$phone}"))) return $this->error('请求速度过快');
        $code = mt_rand(100000, 999999);
        cache("login_sms_code_{$phone}", $code, 300);
        cache("login_sms_send_{$phone}", 1, 180);
        Helper::sendCodeSms($code, $phone);
        return $this->success('短信已发送');
    }

    public function send_reset_phone_sms()
    {
        $this->checkLogin();
        $phone = $this->request->post('phone');
        if (!empty(cache("reset_phone_sms_send_{$phone}"))) return $this->error('请求速度过快');
        $code = mt_rand(100000, 999999);
        cache("reset_phone_sms_code_{$phone}", $code, 300);
        cache("reset_phone_sms_send_{$phone}", 1, 180);
        Helper::sendCodeSms($code, $phone);
        return $this->success('短信已发送');
    }

    public function send_find_password_sms()
    {
        $account = $this->request->post('account');
        if (!empty(cache("reset_password_sms_send_{$account}"))) return $this->error('请求速度过快');
        $user = Users::where('card', $account)->find();
        if (empty($user)) return $this->error('账号不存在');
        if (empty($user->phone)) return $this->error('账号未绑定手机，请联系管理员重置');
        $code = mt_rand(100000, 999999);
        cache("reset_password_sms_code_{$account}", $code, 300);
        cache("reset_password_sms_send_{$account}", 1, 180);
        Helper::sendCodeSms($code, $user->phone);
        return $this->success('短信已发送');
    }
}
